/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lwh.controller.login;

import com.github.pagehelper.util.StringUtil;
import com.lwh.entity.Log;
import com.lwh.entity.Result;
import com.lwh.entity.User;
import com.lwh.service.LogService;
import com.lwh.service.UserService;
import com.lwh.util.*;
import com.lwh.util.checkphone.PhoneFormatCheckUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制器
 */
@Controller
@RequestMapping("/user")
public class LoginController{

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;



    /**
     * 账号密码用户登录请求
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public Map<String,Object> login(String kaptcha, @Valid User user, BindingResult bindingResult, HttpSession session){
        Map<String,Object> map=new HashMap<String,Object>();

        if(StringUtil.isEmpty(kaptcha)){
            map.put("success", false);
            map.put("errorInfo", "请输入验证码！");
            return map;
        }
        if(!session.getAttribute("KAPTCHA_SESSION_KEY").equals(kaptcha)){
            map.put("success", false);
            map.put("errorInfo", "验证码输入错误！");
            return map;
        }

        if(bindingResult.hasErrors()){
            map.put("success", false);
            map.put("errorInfo", bindingResult.getFieldError().getDefaultMessage());
            return map;
        }

        try{

            User currentUser=userService.findByUser(user);
            session.setAttribute("currentUser", currentUser);
            map.put("success", true);
            logService.save(new Log(Log.LOGIN_ACTION,"用户登录",currentUser.getId())); // 写入日志
            return map;
        }catch(Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("errorInfo", "用户名或者密码错误！");
            return map;
        }
    }

    /**
     * 手机登录请求
     */
    @ResponseBody
    @PostMapping("/mbLogin")
    public Map<String,Object> login(String code, String phone, HttpSession session){
        Map<String,Object> map=new HashMap<String,Object>();

        if(StringUtil.isEmpty(code)){
            map.put("success", false);
            map.put("errorInfo", "请输入验证码！");
            return map;
        }
        String phoneCode = (String) redisTemplate.opsForValue().get(phone);
        if(!phoneCode.equals(code)){

            map.put("success", false);
            map.put("errorInfo", "验证码输入错误！");
            return map;
        }
        try{
            User user=userService.findByPhone(phone,code);
            if(user!=null){
                session.setAttribute("currentUser", user);
                map.put("success", true);
                logService.save(new Log(Log.LOGIN_ACTION,"用户手机登录",user.getId())); // 写入日志
                return map;
            }else{
                map.put("errorInfo","手机号码输入错误或不存在");
                return map;

            }

        }catch(Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("errorInfo", "用户名或者密码错误！");
            return map;
        }
    }


    /**
     * 短信发送
     */
    @RequestMapping("/sendCode")
    @ResponseBody
    public Result sendCode(String phone){
        try {
            // 对手机号进行校验
            boolean phoneLegal = PhoneFormatCheckUtils.isPhoneLegal(phone);
            if(!phoneLegal){
                return new Result(false, "手机号不合法");
            }
            String result =userService.sendCode(phone);
            return new Result(true, result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true, "发送成功");
    }



}